<template>
  <view class="wh_750 pageHeight bg_FFFFFF flex align-center flex-column">
    <s-header-title is-display-back title="会员中心" is-fixed background="transparent" showFIcon
                    title-color="#AB6824" @getPageHeight="getPageHeight"></s-header-title>
    <view class="vipTop wh_750 flex align-end justify-around" :style="{
      height:`${height}px`
    }">
      <view class="flex align-center justify-around mb_20" style="width: 750rpx">
        <view class="flex">
          <image :src="sheep.$url.cdn(userInfo.avatar)" style="border-radius: 50%;" class="wh_100 hW_100"></image>
          <view class="flex flex-column ml_16">
            <view class="flex align-center">
              <view class="fs_32 color_AB6822 fw_500">{{ userInfo.nickname }}</view>
              <view v-if="!!userInfo.vip_end_time && new Date().getTime() / 1000 < userInfo.vip_end_time"
                    class="ml_16 wh_140 hW_32 flex align-center justify-center fs_18 fw_500 color_FFFFFF"
                    style="border-radius: 16rpx;background: linear-gradient( 116deg, #FF4206 0%, #FF7950 100%)"
              >
                已开通VIP会员
              </view>
              <view v-else
                    class="ml_16 wh_140 hW_32 flex align-center justify-center fs_18 fw_500 color_FFFFFF"
                    style="background: #919191;border-radius: 16rpx"
              >
                未开通VIP会员
              </view>
            </view>
            <view class="fs_24 color_AB6822 fw_500 mt_8">
              拾亲号: {{ userInfo.uid }}
            </view>
            <view class="fs_24 color_AB6822 fw_400 mt_12">
              会员有效期:
              {{
                !!userInfo.vip_end_time && new Date().getTime() / 1000 < userInfo.vip_end_time ? dayjs(userInfo.vip_end_time * 1000).format('YYYY年MM月DD日') : '未开通'
              }}
            </view>
          </view>
        </view>
        <view class="flex flex-column align-center">
          <image :src="`${IMG_URL}/index/huiyuanzhongxin_biaoshi.png`" class="wh_145 hW_145"></image>
          <view class="wh_154 hW_45 fs_24 color_FFFFFF fw_500 flex align-center justify-center mt_16"
                style="border-radius: 23rpx;background: linear-gradient( 122deg, #F5D598 0%, #FFAC2E 100%);border: 2rpx solid #FFFFFF"
                @click.stop="sheep.$router.go('/pages/extend/extensionCenter', { level: 2 })"
          >
            推广中心
          </view>
        </view>
      </view>
    </view>
    <view class="flex align-end wh_710 hW_70">
      <view class="fs_36 color_AB6822 fw_bold">VIP特权</view>
      <view class="fs_24 color_AB6822 fw_400 ml_8">开通会员可以获得以下权益</view>
    </view>
    <scroll-view class="wh_750" :style="{height: `calc(100vh - ${height}px - 70rpx - 170rpx)`}" scroll-y>
      <view class="wh_750 flex align-center flex-column">
        <view class="wh_530" style="display: grid;grid-template-columns: repeat(3,1fr);grid-column-gap: 69rpx">
          <view v-for="(item,index) in page.list" :key="index" class="flex align-center flex-column mt_38">
            <view class="wh_131 hW_131 flex align-center justify-center"
                  style="background: #FFEED3;border-radius: 20rpx">
              <image :src="item.image" class="wh_50 hW_48"></image>
            </view>
            <view class="fs_24 fw_500 mt_16" style="color:#EAB55E;">{{ item.desc }}</view>
          </view>
        </view>
      </view>
      <view class="hW_80"></view>
    </scroll-view>
    <view class="flex flex-column align-center wh_750 hW_170"
          style="background: #FFF3E0;overflow: hidden"
    >
      <view class="flex align-center wh_313 hW_80 justify-center bg_FF4206 mt_10"
            style="border-radius: 42rpx;"
            @click.stop="purchaseMembership"
            v-if="!!userInfo.vip_end_time && new Date().getTime() / 1000 < userInfo.vip_end_time"
      >
        <text class="ml_13 fs_27 fw_bold color_FFFFFF">会员续费</text>
      </view>
      <view class="flex align-center wh_313 hW_80 justify-center bg_FF4206 mt_10"
            style="border-radius: 42rpx;"
            @click.stop="purchaseMembership"
            v-else
      >
        <text class="fs_36 fw_bold color_FFFFFF">10元/年</text>
        <text class="ml_13 fs_27 fw_bold color_FFFFFF">立即购买</text>
      </view>
      <view class="fs_18 fw_400 mt_11" style="color: #989898">购买即表示阅读同意
        <text class="color_FF4206" @click.stop="sheep.$router.go('/pages/public/richtext',{id:4,title:'会员权益'})">
          《会员协议》
        </text>
      </view>
    </view>
  </view>
</template>

<script setup>
  import SHeaderTitle from '@/sheep/components/s-header-title/s-header-title.vue';
  import { computed, reactive } from 'vue';
  import sheep from '@/sheep';
  import dayjs from 'dayjs';
  import { onLoad } from '@dcloudio/uni-app';
  import { getPx } from '@/sheep/helper';

  const userInfo = computed(() => sheep.$store('user').userInfo);
  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);
  const mp_code = computed(() => sheep.$store('AI').mp_code);
  const version = computed(() => sheep.$store('AI').version);
  const appVersion = computed(() => sheep.$store('app').info.worship_version);

  const page = reactive({
    list: [],
    headerHeight: 0,
  });

  const height = computed(() => {
    // #ifdef MP-WEIXIN
    return page.headerHeight + getPx('225rpx');
    // #endif
    // #ifndef MP-WEIXIN
    return page.headerHeight + getPx('225rpx');
    // #endif
  });

  const vipDisposition = reactive({
    isShow: false,
    goodDetails: {},
  });

  onLoad(async () => {
    const res = await sheep.$api.user.getVipList({
      limit: 12,
    });
    page.list = res.data;
    const { data } = await sheep.$api.goods.ids({ ids: '10' });
    vipDisposition.goodDetails = data[0];
  });

  function getPageHeight(number) {
    page.headerHeight = number;
  }

  async function purchaseMembership() {
    let obj = {};
    let arr = [];
    arr.push({
      goods_id: vipDisposition.goodDetails.id,
      goods_num: 1,
      goods_sku_price_id: vipDisposition.goodDetails.id,
    });
    obj.goods_list = arr;
    obj.is_from = 1;
    obj.order_type = 'goods';
    const { code, data } = await sheep.$api.order.create(obj);
    // #ifdef APP-PLUS
    if (sheep.$platform.device.platform.toLocaleLowerCase() == 'ios' && mp_code.value == appVersion.value) {
      plus.payment.getChannels(async function(channels) {
        for (let i in channels) {
          let channel = channels[i];
          // 获取 id 为 'appleiap' 的 channel
          if (channel.id == 'appleiap') {
            console.log(data.order_sn);
            const data1 = await sheep.$api.order.detail(data.order_sn);
            channel.requestOrder(['io.shiqin.app.com_Member_oneYear'], (res) => {
              applePay(res[0], data.order_sn);
            }, (err) => {
              console.log('内购失败=>', err);
            });
          }
        }
      }, function(e) {
        sheep.$helper.toast('获取iap支付通道失败：' + e.message);
      });
      return;
    }
    // #endif
    sheep.$router.go('/pages/pay/index', {
      orderSN: data.order_sn,
      flag: 1,
    });
  }

  // #ifdef APP-PLUS
  function applePay(order, order_id) {
    uni.showLoading({
      title: '充值中请勿离开',
      mask: true,
    });
    uni.requestPayment({
      provider: 'appleiap',
      orderInfo: {
        productid: order.productid,
      },
      success: (async res => {
        console.log(res);
        uni.hideLoading();
        const { code, msg } = await sheep.$api.user.applePay({
          order_id,
          transactionReceipt: res.transactionReceipt,
          transactionIdentifier: res.transactionIdentifier,
        });
        console.log(code, msg);
        if (code == 1) {
          uni.showModal({
            content: '支付成功',
            showCancel: false,
          });
          vipDisposition.isShow = false;
          sheep.$store('user').updateUserData();
        } else {
          uni.showModal({
            content: '支付失败',
            showCancel: false,
          });
        }
      }),
      fail: (e) => {
        uni.hideLoading();
        uni.showModal({
          content: '支付失败',
          showCancel: false,
        });
      },
    });
  }
  // #endif
</script>


<style scoped lang="scss">
  .vipTop {
    background: url($uni-bg-url-sq + "/index/huiyuanzhongxin_beijing.png") no-repeat;
    background-size: 750rpx 100%;
  }
</style>
